package com.plamwind;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;

import com.google.protobuf.ByteString;
import com.palmwindActivity.proto.PictureProto;
import com.palmwindActivity.proto.ProtoBuf;
import com.palmwindActivity.proto.ProtoBufUtil;


public class ImageSyncService {

	public static boolean serve(ProtoBuf[] protoBuf, OutputStream ouputStream) throws IOException {
		boolean isSuccess = false;
		if (protoBuf != null) {
//			for (int i = 0; i < protoBuf.length; i++) {
//				protoBuf[i].getBufferData();
//				
//			}
			byte[] imageData = readFile("./image/sample_5.jpg");
			if(imageData != null)
			{
				Vector<ProtoBuf>  vector = createProtoBufResp(imageData, "sample_5.jpg", System.currentTimeMillis());
				byte[] readData = ProtoBufUtil.listToByteArray(vector);
				System.out.println("Write bytes: " + readData.length);
				ouputStream.write(readData);
				ouputStream.flush();
				isSuccess = true;
			}
		}
		return isSuccess;
	}

	protected static Vector<ProtoBuf> createProtoBufResp(byte[] data, String name, long timeStamp)
	{
		ProtoBuf protoBuf = new ProtoBuf();
		PictureProto.PicturesResp.Builder pictureRespBuilder = PictureProto.PicturesResp.newBuilder();
		PictureProto.PicturesResp.Picture.Builder pictureBuilder = PictureProto.PicturesResp.Picture.newBuilder();
		pictureBuilder.setImagedata(ByteString.copyFrom(data));
		pictureBuilder.setName(name);
		PictureProto.PicturesResp.Picture picture = pictureBuilder.build();
		pictureRespBuilder.addPictures(picture);
		pictureRespBuilder.setReqAction(IServiceConstants.ACTION_GET_PICTURE);
		pictureRespBuilder.setResponse(0);
		
		PictureProto.PicturesResp resp = pictureRespBuilder.build();
		protoBuf.setBufferData(resp.toByteArray());
		protoBuf.setObjType(IServiceConstants.ACTION_GET_PICTURE);
		Vector<ProtoBuf> vector = new Vector<ProtoBuf>();
		vector.add(protoBuf);
		return vector;
	}
	
	protected static byte[] readFile(String fileName) {
		File file = new File(fileName);
		FileInputStream fis = null;
		byte[] buf = null;
//		InputStreamReader bis = null;
//		BufferedReader bufreader = null;

		try {
			fis = new FileInputStream(file);

			// Here BufferedInputStream is added for fast reading.
//			bis = new InputStreamReader(fis);
//			bufreader = new BufferedReader(bis);
			
			// dis.available() returns 0 if the file does not have more lines.
			int size = fis.available();
			buf = new byte[size];
			fis.read(buf);
			// dispose all the resources after using them.
			
//			bis.close();
//			dis.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally
		{
			try {
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return buf;
	}
}

